package com.ruoyi.common.utils.file;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片压缩工具类
 */
public class ImageCompressUtils {
    private static final Logger log = LoggerFactory.getLogger(ImageCompressUtils.class);

    /**
     * 图片压缩比例
     */
    private static final double DEFAULT_SCALE = 0.8;

    /**
     * 最大宽度
     */
    private static final int MAX_WIDTH = 1920;

    /**
     * 最大高度
     */
    private static final int MAX_HEIGHT = 1080;

    /**
     * 判断是否为图片文件
     */
    public static boolean isImage(MultipartFile file) {
        String extension = FileUploadUtils.getExtension(file);
        for (String ext : MimeTypeUtils.IMAGE_EXTENSION) {
            if (ext.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 压缩图片
     */
    public static byte[] compress(MultipartFile file) throws IOException {
        if (!isImage(file)) {
            return file.getBytes();
        }

        BufferedImage sourceImage = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
        if (sourceImage == null) {
            return file.getBytes();
        }

        int sourceWidth = sourceImage.getWidth();
        int sourceHeight = sourceImage.getHeight();

        // 计算目标尺寸
        int targetWidth = sourceWidth;
        int targetHeight = sourceHeight;

        // 如果图片尺寸超过最大限制，按比例缩小
        if (sourceWidth > MAX_WIDTH || sourceHeight > MAX_HEIGHT) {
            double widthRatio = (double) MAX_WIDTH / sourceWidth;
            double heightRatio = (double) MAX_HEIGHT / sourceHeight;
            double ratio = Math.min(widthRatio, heightRatio);
            targetWidth = (int) (sourceWidth * ratio);
            targetHeight = (int) (sourceHeight * ratio);
        }

        // 创建缩放后的图片
        Image scaledImage = sourceImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
        BufferedImage targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = targetImage.createGraphics();
        g2d.drawImage(scaledImage, 0, 0, null);
        g2d.dispose();

        // 输出压缩后的图片
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String extension = FileUploadUtils.getExtension(file);
        ImageIO.write(targetImage, extension, outputStream);
        return outputStream.toByteArray();
    }
} 